package offer;

public class Solution20 {
    public boolean isNumber(String s) {
        s = s.trim();
        if (s.length() == 0) {
            return false;
        }
        int start = 0;
        if (s.charAt(0) == '+' || s.charAt(0) == '-') {
            start++;
        }
        int i = start;
        while (i < s.length()) {
            char c = s.charAt(i);
            if (c == 'E' || c == 'e') {
                break;
            } else if (c != '.' && !Character.isDigit(c)) {
                return false;
            }
            i++;
        }
        if (!isDecimal(s, start, i - 1)) {
            return false;
        }
        if (i < s.length()) {
            return i < s.length() - 1 && isInteger(s, i + 1, s.length() - 1);
        } else {
            return true;
        }
    }

    private boolean isInteger(String s, int i, int j) {
        if (s.charAt(i) == '+' || s.charAt(i) == '-') {
            i++;
        }
        if (i > j) {
            return false;
        }
        for (int k = i; k <= j; k++) {
            if (!Character.isDigit(s.charAt(k))) {
                return false;
            }
        }
        return true;
    }

    private boolean isDecimal(String s, int i, int j) {
        if (i > j) {
            return false;
        }
        int k = i;
        while (k <= j && s.charAt(k) != '.') {
            k++;
        }
        boolean second;
        if (k >= j || !Character.isDigit(s.charAt(k + 1))) {
            second = false;
        } else {
            second = isInteger(s, k + 1, j);
        }
        boolean first = isInteger(s, i, k - 1);
        if (k == i && second) {
            return true;
        }
        if (k >= j && first) {
            return true;
        }
        return first && second;
    }
}
